//
//  MineController.m
//  Village
//
//  Created by 程虎 on 2017/9/1.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "MineController.h"
#import "MineHeadView.h"
#import "MineTableViewCell.h"
#import "AccountViewController.h"//账号管理
#import "MineVillageViewController.h"//我的村落
#import "AboutMineViewController.h"//关于我们
#import "FeedbackViewController.h"
#import "LoginController.h"
#import "LoginHttpTools.h"
#import "GapfillingViewController.h"//填空
@interface MineController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,UIAlertViewDelegate>
{
    BOOL present;
}
@property (nonatomic , strong) UITableView *mytableview;
@property (nonatomic ,strong) MineHeadView *header;
@property (nonatomic ,strong) NSMutableArray *imageary;
@property (nonatomic ,strong) NSMutableArray *nameary;
@property (nonatomic ,strong) NSMutableArray *nameary1;
@property (nonatomic ,strong) AccountModel *accmodel;
@property (nonatomic ,assign) BOOL isShow;//游客模式提醒
@property(nonatomic, assign)long long mysize;
@end
@implementation MineController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getChacheSize];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (present == YES){
        self.navigationController.navigationBar.hidden = YES;

    }else{
        self.navigationController.navigationBar.hidden = NO;

    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.isShow = YES;
    [self setdata];
    [self BuildView];
    [self loginRefreshInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeLoginRefresh) name:RefreshLoginInfo object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RefreshLoginInfo object:nil];
}

#pragma mark - 登录刷新
- (void)homeLoginRefresh
{
    [self loginRefreshInfo];
    [self.mytableview reloadData];
}

- (void)BuildView{
    _mytableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight - 49 )  style:UITableViewStylePlain];
    _mytableview.dataSource = self;
   _mytableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//去除多余空白行
    _mytableview.backgroundColor = kBackgroundColor;
    _mytableview.delegate = self;
    _mytableview.showsVerticalScrollIndicator = NO;
    _mytableview.showsHorizontalScrollIndicator = NO;
//    _mytableview.scrollEnabled =NO; //设置tableview 不能滚动
    [self.view addSubview:_mytableview];
    
    if (@available(iOS 11.0, *)) {
        _mytableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
//    UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 100)];
//    footview.backgroundColor =kBackgroundColor;
//    _mytableview.tableFooterView = footview;
    
    _header = [[MineHeadView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 134)];
    _mytableview.tableHeaderView = _header;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    
      _header.loginlable.userInteractionEnabled=YES;
    [  _header.loginlable addGestureRecognizer:tap];
    [_header.setButton setImage:[UIImage imageNamed:@"my_set"] forState:UIControlStateNormal];
    [_header.setButton addTarget:self action:@selector(tapAction) forControlEvents:UIControlEventTouchUpInside];
    _header.headImageView.image = [UIImage imageNamed:@"BG-my"];

}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}

- (void)tap{
    
    WeakSelf(weakSelf);
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    id obj = [LongriseRouter openURL:@"LoginController"];
    if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
    {
        id<LongriseRouterDelegater> delegater = obj;
        if(delegater)
        {
            //进行传值，传入统一的block以供B进行回调
            [delegater setParams:dict block:^(id obj) {
               _accmodel = (AccountModel *)obj;
                weakSelf.isShow = YES;
                NSLog(@"mine --- %@",_accmodel.account);
            }];
        }
    }
    if (obj && [obj isKindOfClass:[UIViewController class]]) {
        UIViewController *VC = obj;
        VC.hidesBottomBarWhenPushed = YES;
        present = YES;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:VC];
        [self presentViewController:nav animated:YES completion:nil];
//        [self.navigationController pushViewController:VC animated:YES];
    }
}

#pragma mark - 登录刷新数据
- (void)loginRefreshInfo
{
    if ([Globle getInstance].visitorName.length > 0) {
        //登录状态决定头部
        if([Globle getInstance].account.account.length > 0){
            _header.loginlable.hidden = NO;
            _header.medalImageView.hidden = YES;
            _header.namelable.hidden = YES;
            _header.introducelable.hidden = YES;
        }else{
         [self judgemessage];
        }
    }else{
         [self judgemessage];
    }
    _header.namelable.text = [Globle getInstance].visitorName.length > 0 ? [Globle getInstance].visitorName : ([Globle getInstance].account.nickname.length > 0 ? [Globle getInstance].account.nickname : [Globle getInstance].account.account);
    [_header.portraitImageView sd_setImageWithURL:[NSURL URLWithString:[Globle getInstance].headImg.length > 0 ? [Globle getInstance].headImg : [Globle getInstance].visitorIcon] placeholderImage:[UIImage imageNamed:@"user_icon"]];
    LSLog(@"name ----- %@",_header.namelable.text);
  
}
#pragma mark - 判断是否显示头部职位信息
- (void)judgemessage{
    if ([Globle getInstance].account.account.length > 0){
        if ([Globle getInstance].account.jobunit == nil){
            _header.loginlable.hidden = YES;
            _header.medalImageView.hidden = YES;
            _header.namelable.hidden = NO;
            _header.introducelable.hidden = YES;
            
        }else{
            _header.loginlable.hidden = YES;
            _header.medalImageView.hidden = NO;
            _header.namelable.hidden = NO;
            _header.introducelable.hidden = NO;
            _header.introducelable.text = [NSString stringWithFormat:@"%@·%@",[Globle getInstance].account.jobunit,[Globle getInstance].account.position];
        }
    }else{
        _header.loginlable.hidden = NO;
        _header.medalImageView.hidden = YES;
        _header.namelable.hidden = YES;
        _header.introducelable.hidden = YES;
    }
    
    _header.namelable.text = [Globle getInstance].account.nickname.length > 0 ? [Globle getInstance].account.nickname : ([Globle getInstance].account.account.length > 0 ? [Globle getInstance].account.account : [Globle getInstance].visitorName);
    [_header.portraitImageView sd_setImageWithURL:[NSURL URLWithString:[Globle getInstance].headImg.length > 0 ? [Globle getInstance].headImg : [Globle getInstance].visitorIcon] placeholderImage:[UIImage imageNamed:@"user_icon"]];
    LSLog(@"name11 ----- %@",_header.namelable.text);
  
    
    if (self.isShow) {
        self.isShow = NO;
        if ([Globle getInstance].visitorName.length > 0) {
            [MBProgressHUD showError:@"您现在属于游客登录模式！" toView:self.navigationController.view];
        }
    }
}
#pragma mark - 设置 点击
-(void)tapAction
{
//    if ([Globle getInstance].account.userid == nil){
//        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//        id obj = [LongriseRouter openURL:@"LoginController"];
//        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
//        {
//            id<LongriseRouterDelegater> delegater = obj;
//            if(delegater)
//            {
//                //进行传值，传入统一的block以供B进行回调
//                [delegater setParams:dict block:^(id obj) {
//                    _accmodel = (AccountModel *)obj;
//                    NSLog(@"mine --- %@",_accmodel.account);
//                }];
//            }
//        }
//        if (obj && [obj isKindOfClass:[UIViewController class]]) {
//            UIViewController *VC = obj;
//            VC.hidesBottomBarWhenPushed = YES;
//            present = YES;
//            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:VC];
//            [self presentViewController:nav animated:YES completion:nil];
//        }
//    }else{
//        present = NO;
//        [Tools ToNextName:@"AccountViewController" Params:nil CurrentVC:self Completion:^(id obj) {
//        }];
//     }
    
    GapfillingViewController *tap = [[GapfillingViewController alloc] init];
    [self.navigationController pushViewController:tap animated:YES];
}
- (void)setdata{
    _imageary =[[NSMutableArray alloc] initWithObjects:@"my_article",@"my_village",@"WeChat",@"QQ",@"shareAPP",@"opinion",@"eliminate",@"regards" ,nil];
    _nameary =[[NSMutableArray alloc] initWithObjects:@"我的文章",@"我的村落",@"绑定微信",@"绑定QQ",@"分享APP",@"意见反馈",@"清除缓存",@"关于" ,nil];
    _nameary1 =[[NSMutableArray alloc] initWithObjects:@"我的文章",@"绑定微信",@"绑定QQ",@"分享APP",@"意见反馈",@"清除缓存",@"关于" ,nil];
}
#pragma mark - 数据源方法
// 返回多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
// 返回行数
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0){
        if ([Globle getInstance].account.userid == nil || [Globle getInstance].isNormal){
             return 3;
        }else{
             return 4;
        }
       
    }else{
         return 4;
    }
    
   
}
// 设置cell
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    static NSString *cellID = @"id";
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    float chache=_mysize / 2;
    NSString *mychache;
    if (chache > 0.01) {
        mychache=[NSString stringWithFormat:@"%.2fM",chache];
    }
    else
    { 
        mychache=[NSString stringWithFormat:@"0M"];
    }

    if (cell == nil){
        cell = [[MineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    if ([Globle getInstance].account.userid == nil || [Globle getInstance].isNormal){
        //游客状态或非干部状态
        if (indexPath.section == 0){
            switch (indexPath.row) {
                case 0:
                    //                 cell.rightlable.text = @"未绑定";
                    //                 cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                      cell.leftImageView.image = [UIImage imageNamed:_imageary[indexPath.row]];
                    break;
               
                case 1:
                    if ([Globle getInstance].account.wechatopenid == nil){
                        cell.rightlable.text = @"未绑定";
                        cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                    }else{
                        cell.rightlable.text = @"已绑定";
                        cell.rightlable.textColor = K_Zitihong;
                    }
                      cell.leftImageView.image = [UIImage imageNamed:_imageary[2]];
                    break;
                case 2:
                    if ([Globle getInstance].account.qqopenid == nil){
                        cell.rightlable.text = @"未绑定";
                        cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                    }else{
                        cell.rightlable.text = @"已绑定";
                        cell.rightlable.textColor = K_Zitihong;
                    }
                      cell.leftImageView.image = [UIImage imageNamed:_imageary[3]];
                    break;
                default:
                    break;
            }
            
          
            cell.leftlable.text = _nameary1[indexPath.row];
            
        }else{
            if (indexPath.row == 2){
                cell.rightlable.text = mychache;
            }else{
                cell.rightlable.text = @"";
            }
            
            cell.leftImageView.image = [UIImage imageNamed:_imageary[indexPath.row+4]];
            cell.leftlable.text = _nameary1[indexPath.row+3];
            
        }
    }else{
        if (indexPath.section == 0){
            switch (indexPath.row) {
                case 0:
                    //                 cell.rightlable.text = @"未绑定";
                    //                 cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                    break;
                case 1:
                    if ([Globle getInstance].account.areaid == nil){
                        cell.rightlable.text = @"未绑定";
                        cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                    }else{
                        cell.rightlable.text = @"已绑定";
                        cell.rightlable.textColor = K_Zitihong;
                    }
                    break;
                case 2:
                    if ([Globle getInstance].account.wechatopenid == nil){
                        cell.rightlable.text = @"未绑定";
                        cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                    }else{
                        cell.rightlable.text = @"已绑定";
                        cell.rightlable.textColor = K_Zitihong;
                    }
                    break;
                case 3:
                    if ([Globle getInstance].account.qqopenid == nil){
                        cell.rightlable.text = @"未绑定";
                        cell.rightlable.textColor = [Util colorWithHexString:@"cccccc"];
                    }else{
                        cell.rightlable.text = @"已绑定";
                        cell.rightlable.textColor = K_Zitihong;
                    }
                    break;
                default:
                    break;
            }
            
            cell.leftImageView.image = [UIImage imageNamed:_imageary[indexPath.row]];
            cell.leftlable.text = _nameary[indexPath.row];
            
        }else{
            if (indexPath.row == 2){
                cell.rightlable.text = mychache;
            }else{
                     cell.rightlable.text = @"";
            }
            
            cell.leftImageView.image = [UIImage imageNamed:_imageary[indexPath.row+4]];
            cell.leftlable.text = _nameary[indexPath.row+4];
       
        }
    }
    
    

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];//cell点击之后没有视觉效果
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    return cell;
}
-(void)getChacheSize
{
    _mysize=0;
    NSString *CachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:CachesPath];
    for (NSString *p in files) {
        NSString *path = [CachesPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            //获取文件大小
            long long size = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize];
            _mysize +=size;
        }
    }
    _mysize = _mysize/1024.0/1024.0;
}

#pragma mark - 代理方法
//设置行高
- (CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 50;
}
// 添加每组的组头
- (UIView *)tableView:(nonnull UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 10)];
    view.backgroundColor = kBackgroundColor;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
// 返回每组的组尾
- (UIView *)tableView:(nonnull UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
// 选中某行cell时会调用
- (void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPat
{
    if (indexPat.section == 0){
        if (indexPat.row == 0){
            if ([Globle getInstance].account.userid != nil) {
                present = NO;
                [Tools ToNextName:@"MyArticlesController" Params:nil CurrentVC:self Completion:^(id obj) {
                }];
            }
            else {
                [self tap];
            }
        }
        else if (indexPat.row == 1) {
            if ([Globle getInstance].isNormal == YES) {
                
                if ([Globle getInstance].account.userid != nil) {
                    if ([Globle getInstance].account.wechatopenid.length > 0) {
                        
                    }
                    else {
                        [self bindThridPaty:0];
                    }
                    
                }
                else {
                    [self tap];
                }
            }
            else {
                if ([Globle getInstance].account.userid != nil) {
                    present = NO;
                    if (![Globle getInstance].isNormal) {
                        if ([Globle getInstance].account.areaid.length > 0) {
                            [Tools ToNextName:@"MyVillageController" Params:nil CurrentVC:self Completion:^(id obj) {
                            }];
                        }
                        else {
                            [Tools ToNextName:@"MineVillageViewController" Params:nil CurrentVC:self Completion:^(id obj) {
                                
                            }];
                        }
                    }
                    else {
                        if ([Globle getInstance].account.cardno.length > 0) {
                            [Tools ToNextName:@"VailtalReferViewController" Params:nil CurrentVC:self Completion:^(id obj) {
                                
                            }];
                        }
                        else {
                            [Tools ToNextName:@"CertificateViewController" Params:@"1" CurrentVC:self Completion:^(id obj) {
                            }];
                        }
                    }
                    
                }
                else {
                    [self tap];
                }
            }
        }
        else if (indexPat.row == 2){
            if ([Globle getInstance].account.userid != nil) {
                if ([Globle getInstance].isNormal == YES) {
                    if ([Globle getInstance].account.userid != nil) {
                        if ([Globle getInstance].account.qqopenid.length > 0) {
                            
                        }
                        else {
                           
                            [self bindThridPaty:1];
                        }
                        
                    }
                    else {
                        [self tap];
                    }
                }
                else {
                    if ([Globle getInstance].account.userid != nil) {
                        if ([Globle getInstance].account.wechatopenid.length > 0) {
                            
                        }
                        else {
                            [self bindThridPaty:0];
                        }
                        
                    }
                    else {
                        [self tap];
                    }
                }
            }
            else {
                [self tap];
            }
        }
        else if (indexPat.row == 3){
            if ([Globle getInstance].account.userid != nil) {
                if ([Globle getInstance].account.userid != nil) {
                    if ([Globle getInstance].account.qqopenid.length > 0) {
                        
                    }
                    else {
                        [self bindThridPaty:1];
                    }
                    
                }
                else {
                     [self tap];
                }
            }
            else {
                [self tap];
            }
        }
    }
    else    {
            if (indexPat.row == 0){
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setValue:@"Qr_code_down" forKey:@"localImg"];
                [dict setValue:@"村居通" forKey:@"titles"];
                [dict setValue:@"实时了解村、居新闻和政策，查询村，居委组织机构信息。" forKey:@"content"];
                [dict setValue:@"logo" forKey:@"iconImg"];
                [dict setValue:@"http://192.168.7.214:8072/Studio/LEAP/web/download.html" forKey:@"url"];
                
                present = NO;
                [Tools ToNextName:@"ShareViewController" Params:dict CurrentVC:self Completion:^(id obj) {
                    
                }];
            }
            else if (indexPat.row == 1){
                if ([Globle getInstance].account.userid == nil){
                     [self tap];
                }else{
                    present = NO;
                    [Tools ToNextName:@"FeedbackViewController" Params:nil CurrentVC:self Completion:^(id obj) {
                    }];
                    
                }
                
                
            }
            else if (indexPat.row == 2){
                if (_mysize >=0.01) {
                    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您确定要清除缓存吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
                }
                else
                {
                    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"已经很干净了" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alert show];
                }
                
            }
            else if (indexPat.row == 3){
                present = NO;
                [Tools ToNextName:@"AboutMineViewController" Params:nil CurrentVC:self Completion:^(id obj) {
                    
                }];
            }
        }
}

#pragma mark - 第三方绑定 0 微信 1 QQ
- (void)bindThridPaty:(NSInteger )types
{
    [[ShareFunction shareInstance] loginOtherWaysWithType:types ToController:self];
    WeakSelf(weakSelf);
    [ShareFunction shareInstance].loginBlock = ^(UMSocialUserInfoResponse *resp) {
        LSLog(@"第三方登录 ------ %@",resp.name);
        //判断如果已绑定 置空临时数据
        [Globle getInstance].visitorWXID = types == 0 ? resp.openid : nil;
        [Globle getInstance].visitorQQID = types == 1 ? resp.openid : nil;
        [Globle getInstance].visitorName = resp.name;
        [Globle getInstance].visitorIcon = resp.iconurl;
        
        [weakSelf accountBindQQID:types == 0 ? @"" : [Globle getInstance].visitorQQID WXID:types == 0 ? [Globle getInstance].visitorWXID : @""];
    };
}


#pragma mark - 清除缓存提示
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
    }
    else if (buttonIndex ==1)
    {
        NSString *CachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:CachesPath];
        for (NSString *p in files)
        {
            NSError *error;
            NSString *path = [CachesPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path])
            {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                //获取文件大小
                long long size = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize];
                NSLog(@"---==%lf",size/1024.0/1024.0);
            }
        }
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:@"清除完毕" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        _mysize = 0;
        [alert show];
        [_mytableview reloadData];
    }
}

#pragma mark - 绑定微信、QQ
- (void)accountBindQQID:(NSString *)QQID WXID:(NSString *)WXID
{
    WeakSelf(weakSelf);
    [MBProgressHUD showMessage:@"正在加载..." toView:self.navigationController.view];
    [LoginHttpTools AccountBindWithQQID:QQID WithWXID:WXID Success:^(NSDictionary *valueDict) {
        [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
        [MBProgressHUD showSuccess:valueDict[@"message"]  toView:weakSelf.navigationController.view Completion:^{
            [[Globle getInstance] saveAccountInfo:valueDict[@"data"]];
            [weakSelf.mytableview reloadData];
        }];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
        [MBProgressHUD showError:error toView:weakSelf.navigationController.view];
    }];
}
@end


